package eu.flatworld.android.ontop;

import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.j256.ormlite.android.apptools.OpenHelperManager;

import eu.flatworld.android.ontop.db.ChecklistItem;
import eu.flatworld.android.ontop.db.DatabaseHelper;
import eu.flatworld.android.ontop.db.Memo;
import eu.flatworld.android.ontop.db.Util;

public class ChecklistFragment extends SherlockListFragment {
	private DatabaseHelper dbh = null;
	
	Memo currentMemo =  null;	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(Main.LOGTAG, "create checklistfragment");
		super.onCreate(savedInstanceState);
		
		if(getArguments().getSerializable("memo") != null) {
			currentMemo = (Memo)getArguments().getSerializable("memo");
		}
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		registerForContextMenu(this.getListView());
		setHasOptionsMenu(true);
		ActionBar bar = getSherlockActivity().getSupportActionBar();
		if(currentMemo != null) {
			Toast.makeText(getActivity(),
					"Got memo: " + currentMemo,
					Toast.LENGTH_SHORT).show();			
			bar.setSubtitle(currentMemo.getName());
		}		
		loadChecklistItemList(currentMemo);
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putSerializable("memo", currentMemo);
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		if (dbh != null) {
			OpenHelperManager.releaseHelper();
			dbh = null;
		}
	}

	ChecklistItem createCheclistItem(Memo memo, String name) {
		try {
			return Util.createCheclistItem(getDbHelper(), memo, name);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_creating_the_item);
			Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
		return null;
	}

	void deleteChecklistItem(ChecklistItem ci) {
		try {
			Util.deleteChecklistItem(getDbHelper(), ci);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_deleting_the_item);
			Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
	}

	void loadChecklistItemList(Memo memo) {
		try {
			List<ChecklistItem> lm = Util.loadChecklistItemList(getDbHelper(), memo);			
			ChecklistItemAdapter adapter = new ChecklistItemAdapter(getActivity(), lm);
			setListAdapter(adapter);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_loading_the_items);
			Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
	}

	private DatabaseHelper getDbHelper() {
		if (dbh == null) {
			dbh = OpenHelperManager.getHelper(getActivity(), DatabaseHelper.class);
		}
		return dbh;
	}

	@Override
	public void onResume() {
		super.onResume();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// This uses the imported MenuItem from ActionBarSherlock
		if (item.getItemId() == OnTopActivity.MENU_ADD_ID) {
			final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
			alert.setTitle(R.string.enter_item_name_);
			// Set an EditText view to get user input
			final EditText input = new EditText(getActivity());
			alert.setView(input);
			alert.setPositiveButton(R.string.ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							String value = input.getText().toString();
							if(value.trim().length() == 0) {
								value = getString(R.string.no_name);
							}
							ChecklistItem ci = createCheclistItem(currentMemo, value);
							loadChecklistItemList(currentMemo);							
							return;
						}
					});
			alert.setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							return;
						}
					});
			final Dialog d = alert.create();
			input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			    @Override
			    public void onFocusChange(View v, boolean hasFocus) {
			        if (hasFocus) {
			            d.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
			        }
			    }
			});
			d.show();
			return true;
		}

		//Toast.makeText(this, "Got click: " + item.toString(), Toast.LENGTH_SHORT).show();
		return true;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		ChecklistItemAdapter cia = (ChecklistItemAdapter) getListAdapter();
		ChecklistItem ci = cia.getItem(position);
		ci.setChecked(!ci.isChecked());
		cia.notifyDataSetChanged();
		try {
			Util.update(getDbHelper(), ci);
		} catch (java.sql.SQLException ex) {
			String s = getString(R.string.error_updating_item);
			Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
			Log.e(Main.LOGTAG, s, ex);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		menu.clear();
		// menu.setHeaderIcon(R.drawable.icon);
		// menu.setHeaderTitle(R.string.options);

		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		int position = info.position;
		Adapter adapter = ((ListView) v).getAdapter();
		ChecklistItem ci = (ChecklistItem) adapter.getItem(position);
		menu.setHeaderTitle(ci.getName());
		menu.add(R.string.delete);
	}

	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {
		// Recupera l'oggetto associato alla lista
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		ChecklistItem ci = (ChecklistItem) getListAdapter().getItem(info.position);
		deleteChecklistItem(ci);
		loadChecklistItemList(currentMemo);
		return true;
	}	
}